﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/*
 * 这个脚本主要是创建玩家移动控制
 */
[SerializeField]
public class PlayerController : MonoBehaviour
{
    //水平最小
    public float hMin = -6.9f;
    //水平最大
    public float hMax = 6.9f;
    //垂直最小
    public float vMin = 0f;
    //垂直最大
    public float vMax = 17.5f;

    public float speed = 10f;

    public GameObject bolt; //子弹
    public Transform spawnPos; //子弹的发射位置
    public float fireRate = 0.1f; //发射时间间隔
    public float nextFire;
    //子弹发射音频
    public AudioClip clip;
    //声明组件
    public AudioSource audioSource;


    //unity5以后需要声明变量
    Rigidbody rigidbody1;
    

    void FixedUpdate()
    {
        //绑定组件
        rigidbody1 = this.GetComponent<Rigidbody>();
        
        //获得输入的水平移动信息
        float h = Input.GetAxis("Horizontal");
        //获得输入的垂直移动信息
        float v = Input.GetAxis("Vertical");
        Vector3 move = new Vector3(h,0,v);

        //设定物理刚体的位置
        //限制物理刚体的左右，上下极限位置。
        rigidbody1.position = new Vector3(
            Mathf.Clamp(rigidbody1.position.x,hMin,hMax), 
            0,
            Mathf.Clamp(rigidbody1.position.z,vMin,vMax)
            ) ;
        //设定物理刚体速度
        rigidbody1.velocity = speed * move;
    }

    void Update()
    {
        //按下Space键发射子弹
        //创建频率约束
        if (Input.GetKeyDown(KeyCode.Space) && Time.time > nextFire ) {
            nextFire = Time.time + fireRate;
            //生成子弹实体
            Instantiate(bolt, spawnPos.position,spawnPos.rotation);
            //添加声音特效
            audioSource = this.GetComponent<AudioSource>(); 
            audioSource.PlayOneShot(clip);
        }
    }
}
